package com.zatech.cgnci.project.base.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;

public class SM4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ALGORITHM_NAME = "SM4";
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    /**
     * SM4 加密
     */
    public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
        if (key.length != 16) {
            throw new IllegalArgumentException("SM4 key must be 128 bits (16 bytes)");
        }
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(data);
    }

    /**
     * SM4 解密
     */
    public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(encryptedData);
    }

    /**
     * 加密并返回 Base64 编码的字符串
     */
    public static String encryptBase64(String key, String data) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key); // 解码 Base64 密钥
        if (keyBytes.length != 16) {
            throw new IllegalArgumentException("SM4 key must be 128 bits (16 bytes)");
        }
        byte[] dataBytes = data.getBytes();
        byte[] encryptedBytes = encrypt(keyBytes, dataBytes);
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密 Base64 编码的加密数据
     */
    public static String decryptBase64(String key, String encryptedData) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key); // 解码 Base64 密钥
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData); // 解码 Base64 加密数据
        byte[] decryptedBytes = decrypt(keyBytes, encryptedBytes);
        return new String(decryptedBytes);
    }

    /**
     * 生成 SM4 密钥（16 字节，Base64 编码）
     */
    public static String generateSM4Key() {
        SecureRandom random = new SecureRandom();
        byte[] key = new byte[16]; // SM4 密钥长度为 16 字节
        random.nextBytes(key);
        return Base64.getEncoder().encodeToString(key); // 转换为 Base64 字符串
    }

    public static void main(String[] args) throws Exception {
        // 生成 SM4 密钥（16 字节，Base64 编码）
        //String sm4Key = generateSM4Key(); // 替换为生成的 SM4 密钥
        String sm4Key = "02tl1KaOXbYz+G7oQr9KHg=="; // 替换为生成的 SM4 密钥
        System.out.println("sm4Key: " + sm4Key);
        String password = "123456"; // 替换为你的数据库密码

        // 加密密码
        String encryptedPassword = SM4Util.encryptBase64(sm4Key, password);
        System.out.println("Encrypted Password: " + encryptedPassword);

        // 解密密码（验证）
        String decryptedPassword = SM4Util.decryptBase64(sm4Key, encryptedPassword);
        System.out.println("Decrypted Password: " + decryptedPassword);
    }
}